import { constantRoutes, asyncRoutes } from '@/router'
import Layout from '@/layout/index'
import { getUserAuth } from "@/api/platform/account";
import { getuserCode } from "@/utils/userCode";

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

const state = {
  routes: [],
  addRoutes: [],
  permissions: [],
  userCode: getuserCode()
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    const page = []
    return new Promise(resolve => {
      let accessedRoutes
      if (roles[0].roleCode === 'admin') {
        // 如果具有admin 权限则全页面可访问
        accessedRoutes = asyncRoutes || []
      } else {
        roles.forEach(ele => {
          page.push(ele.page)
        })
        accessedRoutes = findPagePath(page, asyncRoutes)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  getUserAuth({ commit }, userCode) {
    return new Promise((resolve) => {
      getUserAuth({ 'searchParams': { 'userCode': userCode, 'isBlackList': '1' } }).then(res => {
        if (res.retCode === '200') {
          if (res.responseBody) {
            commit('SET_PERMISSIONS', res.responseBody)
            resolve(res.responseBody)
          }
        } else {
          console.log(res)
        }
      })
    })
  },
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(page, asyncRouterMap) {
  console.log(page)
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(page, route.children)
    }
    return true
  })
}

function findPagePath(pagelist, routes) {
  try {
    const res = []
    routes.forEach(ele1 => {
      // 第一层遍历，找第一级
      if (ele1.children) {
        const tmp1 = { ...ele1 }
        tmp1.children = []
        ele1.children.forEach(ele2 => {
          // console.log(ele)第二层遍历，找第二级
          const tmp2 = { ...ele2 }
          tmp2.children = []
          if (ele2.children) {
            // 最后一级的搜索了
            ele2.children.forEach(ele3 => {
              if (pagelist.some(page => page === ele3.path)) {
                tmp2.children.push(ele3)
              }
            })
            if (tmp2.children.length > 0) {
              tmp1.children.push(tmp2)
            }
          } else {
            if (pagelist.some(page => page === ele2.path)) {
              tmp1.children.push(ele2)
            }
          }
        })
        if (tmp1.children.length > 0) {
          res.push(tmp1)
        }
      } else {
        // 第一级的请求
        if (pagelist.some(page => page === ele1.path)) {
          res.push(ele1)
        }
      }
    })
    res.push({ path: '*', redirect: '/404', hidden: true })
    return res
  } catch (e) {
    console.log('路由加载异常')
    console.log(e)
  }
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
